package vashion.azeroth.core.manager.personal;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import vashion.azeroth.common.math.RandomUtil;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.core.common.NeedOperateFlow;
import vashion.azeroth.core.dao.BaseDao;
import vashion.azeroth.core.manager.impl.BaseManagerImpl;
import vashion.azeroth.core.personal.dao.PersonalInviteCodeDao;
import vashion.azeroth.core.personal.pojo.PersonalInviteCode;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.pojo.common.OperateFlowEnum;

@Service
public class PersonalInviteCodeManager extends BaseManagerImpl<PersonalInviteCode> {
	
    @Autowired
    private PersonalInviteCodeDao personalInviteCodeDao;
    
    @NeedOperateFlow(operateIdArgLocation = 1, operateFlowEnum = OperateFlowEnum.MEMBER)
	public Integer generateInviteCode(PersonalMember member, long operatorId) {
		PersonalInviteCode inviteCode = new PersonalInviteCode();
		inviteCode.setCode(RandomUtil.getCharAndNumr(6));
		PersonalInviteCode oldInviteCode = getInviteCodeByCode(inviteCode);
		if(null == oldInviteCode) {
			inviteCode.setMemberId(member.getMemberId());
			inviteCode.setMemberName(member.getMemberName());
			inviteCode.setStatus(AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.unused);
			inviteCode.setTimeAdd(new Date());
			inviteCode.setTimeEdit(new Date());
			
			return personalInviteCodeDao.save(inviteCode);
		} else {
			//邀请码重复递归调用重新生成
			return generateInviteCode(member, operatorId);
		}
		
	}
	
	public PersonalInviteCode getInviteCodeByCode(PersonalInviteCode inviteCode) {
		return personalInviteCodeDao.getInviteCodeByCode(inviteCode);
	}
	
	public PersonalInviteCode getInviteCodeByUseMemberName(String useMemberName) {
		List<PersonalInviteCode> myInviteCode = personalInviteCodeDao.getByUseMemberName(useMemberName);
		if (CollectionUtils.isEmpty(myInviteCode)) {
			return null;
		}
		return personalInviteCodeDao.getByUseMemberName(useMemberName).get(0);
	}
    
	@Override
	public BaseDao<PersonalInviteCode> getDao() {
		return personalInviteCodeDao;
	}

	public int findCntByMemberId(PersonalMember member) {
		return personalInviteCodeDao.findCntByMemberId(member);
	}

}
